package projects.jnurse.ioc.core;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.ClassAdapter;

/**
 * Created by Adil Naji.
 * User: XP-170708
 * Date: 14 nov. 2008
 * Time: 20:45:38
 */
public class AnnotationScanner {

    private static AnnotationScanner instance = new AnnotationScanner();

    public static Class nextToInject;

    String aliasToResolve;

    Class nextToScan;
    Object currentObjectValue;

    DependencyStore store = DependencyStore.instance;

    IocClassLoader cl = new IocClassLoader();

    public Class scan(Class clazz) {
        //nextToScan = clazz;
        //return this;
        try {

            ClassReader cr = new ClassReader(clazz.getName());
            ClassWriter cw = new ClassWriter(cr, 0);
            ClassAdapter ca = new IocFieldAdapter(cw);
            //ClassVisitor cv = new IocClassVisitor();
            cr.accept(ca, 0);
            byte[] b = cw.toByteArray();
            cr.getClass().getClassLoader();
            return cl.defineClass(clazz.getName(), b);
        } catch(Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public <T> T fill(Class clazz) {
        try {
            return (T)scan(clazz).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void thatHas(String alias) {

    }

    public void inject(String alias) {
        currentObjectValue = store.resolve(alias);
    }

    public static AnnotationScanner instance() {
        return instance;
    }
}
